package com.taijihuabao.common.commonutils;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 业务主键生成工具类
 *
 * @author wang
 */
@Component
public class BusinessIdUtil {

    private static RedisTemplate redisTemplate;

    /**
     * 根据日期生成有序编码
     *
     * @return
     */
    public static String createBusinessId() {
        String code;
        String date = DateFormatUtil.formatDateCrowd(new Date());
        //Increment an integer value stored as string value under key by one.
        Long serialNum = redisTemplate.opsForValue().increment(date, 1L);
        //设置过期时间，TimeUnit中有多种枚举类型,设置为1天
        redisTemplate.expire(date, 1, TimeUnit.DAYS);
        //String. format的格式化用法-- %03d意 思为保留3位数，不足三位数字前面补0
        code = date + String.format("%03d", serialNum);
        return code;

    }

    /**
     * 结合传入前缀生成有序编码
     *
     * @param prefix 前缀
     * @return
     */
    public static String createBusinessId(String prefix) {
        String code;
        String date = DateFormatUtil.formatDateCrowd(new Date());
        //Increment an integer value stored as string value under key by one.
        Long serialNum = redisTemplate.opsForValue().increment(prefix + date, 1L);
        //设置过期时间，TimeUnit中有多种枚举类型,设置为1天
        redisTemplate.expire(prefix + date, 1, TimeUnit.DAYS);
        //String. format的格式化用法-- %03d意 思为保留3位数，不足三位数字前面补0
        code = prefix + date + String.format("%03d", serialNum);
        return code;
    }

    @Resource
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        BusinessIdUtil.redisTemplate = redisTemplate;
    }

}
